<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/3/5
 * Time: 17:37
 */

namespace app\common\lib;


use think\Model;

class BaseModel extends Model
{
    const JSON_FIELDS = [];

    public function encodeJSON() {
        foreach (static::JSON_FIELDS as $FIELD) {
            if (isset($this->$FIELD) && (is_array($this->$FIELD) || is_object($this->$FIELD))) {
                $this->$FIELD = json_encode($this->$FIELD,JSON_UNESCAPED_UNICODE);
            }
        }
    }
    public function decodeJSON() {
        foreach (static::JSON_FIELDS as $FIELD) {
            if (isset($this->$FIELD) && is_string($this->$FIELD)) {
                $this->$FIELD = json_decode($this->$FIELD);
            }
        }
    }

    /**
     * @param mixed $data
     * @param array $with
     * @param bool $cache
     * @return null|static
     */
    public static function get($data, $with = [], $cache = false)
    {
        $model = parent::get($data, $with, $cache);
        if ($model) $model->decodeJSON();
        return $model;
    }

    /**
     * @param array $data
     * @param array $where
     * @param null $sequence
     * @return false|int
     */
    public function save($data = [], $where = [], $sequence = null)
    {
        $this->encodeJSON();
        $result = parent::save($data, $where, $sequence);
        $this->decodeJSON();
        return $result;
    }

    public static function all($data = null, $with = [], $cache = false)
    {
        $list = parent::all($data, $with, $cache);
        foreach ($list as $item) {
            $item->decodeJSON();
        }
        return $list;
    }
}